const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database().collection("user");

// 获取openId云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const req = event.data
  let data = {};
  if("telphone" in req)
  {
    data["telphone"] = req["telphone"]
  }

  if("grade" in req)
  {
    if( [1,2,3,4].indexOf(req["grade"]) > -1)
    {
      data["grade"] = req["grade"]
    }
  }

  if(Object.keys(data).length == 0)
  {
    return {
      code:400,
      data:{},
      msg:"empty or wrong param"
    }
  }
  else
  {
    const result = await db.where({openid:wxContext.OPENID}).update({data:data})
    let updated = result.stats.updated
    if(updated == 0)
    {
        return {
          code:404,
          data:{
            updated:updated
          },
          msg:"not change"
        }
    }
    else
    {
      return {
        code:200,
        data:{
          updated:updated
        },
        msg:"success"
      }
    }
  }

  return 
};
